import 'package:ai_data_capture/bean/ConfigFileBean.dart';
import 'package:ai_data_capture/bean/FlowBean.dart';
import 'package:ai_data_capture/page/main/logic.dart';
import 'package:ai_data_capture/req/api/ConfigApi.dart';
import 'package:ai_data_capture/req/api/FlowApi.dart';
import 'package:ai_data_capture/req/api/TaskApi.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'state.dart';

class AddTempBean {
  final bool isAdd;
  final ConfigFileBean? configFileBean;
  final FlowBean? flowBean;
  final String? desc;
  final String? id;

  AddTempBean(
      {required this.isAdd,
      required this.configFileBean,
      required this.flowBean,
      required this.desc,
      required this.id});
}

class AddTemplateLogic extends GetxController {
  final AddTemplateState state = AddTemplateState();
  final parentLogic = Get.find<MainLogic>();
  var descController = TextEditingController();
  late AddTempBean bean;
  @override
  void onInit() {
    super.onInit();
    bean = Get.arguments as AddTempBean;
    state.flow.value = bean.flowBean;
    state.selectedConfig.value = bean.configFileBean;
    descController.text = bean.desc ?? "";
  }

  Future selectConfig() async {
    var configs = await ConfigApi.getConfigFile();
    ConfigFileBean? res = await Get.dialog(PopScope(
      canPop: true,
      child: Center(
        child: Container(
          padding: const EdgeInsets.all(10),
          width: Get.width * 0.8,
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(10)),
          child: SingleChildScrollView(
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              const SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: Center(
                      child: Text("选择配置",
                          style: TextStyle(fontWeight: FontWeight.bold)))),
              if (configs.isEmpty)
                const Center(child: Text("暂无配置，请添加"))
              else
                ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: configs.length,
                    itemBuilder: (BuildContext context, int index) {
                      var config = configs[index];
                      return InkWell(
                        onTap: () {
                          Get.back(result: config);
                        },
                        child: Container(
                            padding: const EdgeInsets.all(5),
                            decoration: BoxDecoration(
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                      color: Colors.grey.shade50,
                                      blurRadius: 5,
                                      spreadRadius: 5)
                                ]),
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text("配置编号：${config.id}"),
                                  Text("配置描述：${config.description}")
                                ])),
                      );
                    })
            ]),
          ),
        ),
      ),
    ));
    if (res == null) {
      return;
    }
    state.selectedConfig.value = res;
  }

  Future<void> selectFlow() async {
    var flows = await FlowApi.getFlow();
    FlowBean? res = await Get.dialog(PopScope(
        canPop: true,
        child: Center(
            child: Container(
                padding: const EdgeInsets.all(10),
                width: Get.width * 0.8,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: SingleChildScrollView(
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                      const SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: Center(
                              child: Text("选择流程",
                                  style:
                                      TextStyle(fontWeight: FontWeight.bold)))),
                      if (flows.isEmpty)
                        const Center(child: Text("暂无流程，请添加"))
                      else
                        ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: flows.length,
                            itemBuilder: (BuildContext context, int index) {
                              var config = flows[index];
                              return InkWell(
                                  onTap: () {
                                    Get.back(result: config);
                                  },
                                  child: Container(
                                      padding: const EdgeInsets.all(5),
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          boxShadow: [
                                            BoxShadow(
                                                color: Colors.grey.shade50,
                                                blurRadius: 5,
                                                spreadRadius: 5)
                                          ]),
                                      child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text("流程步骤：${config.step}"),
                                            Text("配置描述：${config.description}")
                                          ])));
                            })
                    ]))))));
    if (res == null) {
      return;
    }

    state.flow.value = res;
  }

  Future<void> addTaskTemplate() async {
    if (descController.text.isEmpty) {
      showToast("请输入模版描述");
      return;
    }
    if (state.selectedConfig.value == null) {
      showToast("请选择配置文件");
      return;
    }
    if (state.flow.value == null) {
      showToast("请选择流程");
      return;
    }
    try {
      await TaskApi.addTemp(
          id: bean.id,
          configid: "${state.selectedConfig.value?.id}",
          flowid: "${state.flow.value?.id}",
          desc: descController.text);
      Get.back();
    } catch (e) {
      print(e);
      showToast("添加失败");
    }
  }
}
